<template>
    <div>
        <el-form inline>
            <el-form-item label="名称">
                <el-input placeholder="名称" v-model="searchTempObj.name" />
            </el-form-item>
            <el-form-item label="状态">
                <el-select v-model="searchTempObj.enabled" clearable  placeholder="请选择">
                    <el-option v-for="(item,index) in activeList" :key="index" :label="item.name" :value="item.value"></el-option>
                </el-select>
            </el-form-item>
            <el-button type="primary" icon="el-icon-search" @click="search">查询</el-button>
            <el-button @click="clearSearch">清空</el-button>
        </el-form>
  
        <div style="margin-bottom: 20px">
            <el-button type="primary" v-if="addButtons" @click="handleAdd">添加</el-button>
        </div>
  
        <el-table border stripe :data="dataList" v-loading="listLoading" >
  
            <el-table-column type="index" label="序号" width="80" align="center"></el-table-column>
            <el-table-column prop="name" label="任务名称" />
            
            <el-table-column prop="task" label="执行代码" />
            <el-table-column prop="disable" label="是否启用">
                <template slot-scope="{row,$index}">
                    <el-switch v-model="row.enabled" :disabled="!editButtons" @change="changeStatus(row,$index)"></el-switch>
  
                </template>
            </el-table-column>
            <el-table-column prop="schedule" label="定时策略"/>
            <el-table-column prop="total_run_count" label="已执行次数" width="180" />
            <el-table-column prop="last_run_at" label="最后执行时间" width="180" />
  
  
            <el-table-column label="操作" width="300" align="center">
                <template slot-scope="{row}">
                    <HintButton size="mini" type="primary" icon="el-icon-edit" title="修改任务" v-if="editButtons" @click="handleUpdate(row)" />
                    <HintButton size="mini" type="danger" icon="el-icon-delete" title="删除任务" v-if="delButtons" @click="handleDelete(row)" />
                </template>
            </el-table-column>
        </el-table>
  
        <!-- 分页组件 -->
        <el-pagination :current-page="page" :total="total" :page-size="limit" :page-sizes="limitArr" :pager-count="pagerCount"
            @current-change="getData" @size-change="handleSizeChange" style="padding: 20px 0;"
            layout="prev, pager, next, jumper, ->, sizes, total" />
  
            <el-dialog :title="dataInfo.id?'修改任务':'添加任务'" :visible.sync="dialogVisible" :before-close="clearData" >
            <el-form :model="dataInfo" :rules="rules" ref="roleForm" label-width="80px">
                <el-form-item label="名称" prop="name">
                    <el-input v-model="dataInfo.name"></el-input>
                </el-form-item>
                <el-form-item label="代码" prop="task">
                    <el-input v-model="dataInfo.task"></el-input>
                </el-form-item>
                
                <el-form-item label="时间策略">
                    <el-radio-group v-model="dataInfo.time_type">
                        <el-radio label="interval">间隔</el-radio>
                        <el-radio label="crontab">crontab</el-radio>
                        <el-radio label="clocked">定时</el-radio>
                    </el-radio-group>
                </el-form-item>
                <el-form-item label="每隔" v-show="dataInfo.time_type == 'interval'" >
                    <el-input-number v-model="dataInfo.interval_info.every" :min="1" :precision="0"></el-input-number>
                    <el-select v-model="dataInfo.interval_info.period" placeholder="请选择" style="width: 100px;margin-left: 10px;" >
                        <el-option v-for="item in periodOptions" :key="item.value" :label="item.label" :value="item.value"></el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="分钟" prop="crontab_info.minute" v-show="dataInfo.time_type == 'crontab'">
                    <el-input v-model="dataInfo.crontab_info.minute" placeholder='定时的分钟，* 表示全部 多个时间数用,隔开例如 10,20' ></el-input>
                </el-form-item>
                <el-form-item label="小时" prop="crontab_info.hour" v-show="dataInfo.time_type == 'crontab'" >
                    <el-input v-model="dataInfo.crontab_info.hour" placeholder='定时的时间，* 表示全部 多个时间数用,隔开例如 8,9' ></el-input>
                </el-form-item>
                <el-form-item label="每周的天" prop="crontab_info.day_of_week" v-show="dataInfo.time_type == 'crontab'" >
                    <el-input v-model="dataInfo.crontab_info.day_of_week" placeholder='每周第几天，* 表示全部 多个天数用,隔开例如 1,5 星期日是0或7，星期一是1' ></el-input>
                </el-form-item>
                <el-form-item label="每月的天" prop="crontab_info.day_of_month" v-show="dataInfo.time_type == 'crontab'" >
                    <el-input v-model="dataInfo.crontab_info.day_of_month" placeholder='每个月的第几天，* 表示全部 多个天数用,隔开例如 1,5' ></el-input>
                </el-form-item>
                <el-form-item label="每年的月" prop="crontab_info.month_of_year" v-show="dataInfo.time_type == 'crontab'" >
                    <el-input v-model="dataInfo.crontab_info.month_of_year" placeholder='月份(1-12)，* 表示全部 多个月份用,隔开例如 1,5' ></el-input>
                </el-form-item>
                
                <el-form-item label="定时日期" prop="clocked_info.clocked_time" v-show="dataInfo.time_type == 'clocked'" >
                    <el-date-picker v-model="dataInfo.clocked_info.clocked_time" type="datetime" placeholder="选择日期时间" default-time="00:00:00"> </el-date-picker>
                </el-form-item>
                
                <el-form-item label="列表参数" prop="args">
                    <el-input v-model="dataInfo.args" placeholder='JSON encoded positional arguments,(Example: ["arg1", "arg2"])'></el-input>
                </el-form-item>
                <el-form-item label="字典参数" prop="kwargs">
                    <el-input v-model="dataInfo.kwargs" placeholder='JSON encoded keyword arguments,(Example: {"argument": "value"})'></el-input>
                </el-form-item>
                <el-form-item label="描述" prop="description">
                    <el-input type="textarea" placeholder="任务描述" v-model="dataInfo.description" ></el-input>
                </el-form-item>
                <el-form-item label="是否启用" prop="enabled">
                    <el-radio-group v-model="dataInfo.enabled">
                        <el-radio v-for="(item, index) in activeList" :key="index" :label="item['value']">{{item['name']}}</el-radio>
                    </el-radio-group>
                </el-form-item>
                <el-form-item label="执行一次" prop="one_off">
                  <el-switch v-model="dataInfo.one_off" ></el-switch><span style="margin-left: 10px;color: #DCDFE6;font-size: 12px;">开启后任务执行一次便关闭</span>
              
                </el-form-item>
                
            </el-form>
  
            <div slot="footer">
                <el-button @click="clearData">取 消</el-button>
                <el-button :loading="buttonLoading" type="primary" @click="saveData">确 定</el-button>
                
            </div>
        </el-dialog>
    </div>
  </template>
  
  <script>
import { resetRouter } from '@/router';
var validateOneOff = (rule, value, callback) => {

    if (!value) {
        return callback(new Error('必须开启'));
    }else{
        callback()
    }
}
export default {

    name: 'Task',

    data() {

        return {
            total: 0, // 总记录数
            page: 1, // 当前页码
            limit: this.$util.page.limit, // 每页记录数
            limitArr:this.$util.page.size,
            pagerCount:this.$util.page.pagerCount,
            activeList:this.$util.activeList,
            dataList: [],
            dataInfo: {
                time_type:'interval',
                enabled:true,
                interval_info:{every:1,period:'days'},
                crontab_info:{},
                clocked_info:{},
                one_off:false
            },
            // 搜索提交
            searchObj: {
                name: '',
                enabled:'',
            },
            
            // 搜索临时存储
            searchTempObj: {
                name: '',
                enabled:'',
            },

            // 数据列表加载
            listLoading:true,

            dialogVisible:false,
            // 按钮加载状态
            buttonLoading: true,
            periodOptions: [
                {
                    value: "days",
                    label: "天",
                },
                {
                    value: "hours",
                    label: "小时",
                },
                {
                    value: "minutes",
                    label: "分钟",
                },
                {
                    value: "seconds",
                    label: "秒",
                },
            ],
            
           
        }
    },
    computed:{
        addButtons(){
            return this.$util.isButton('system.task.add')
        },
        editButtons(){
            return this.$util.isButton('system.task.edit')
        },
        delButtons(){
            return this.$util.isButton('system.task.delete')
        },
        rules() {
            let rulesData = {
                name: [{ required: true, message: "请输入名称", trigger: "blur" }],
                task: [{ required: true, message: "请输入任务", trigger: "blur" }],
            }
            let timeType = this.dataInfo.time_type
            if (timeType == "crontab") {
                rulesData["crontab_info.minute"] = [{ required: true, message: "请输入分钟", trigger: "blur" }]
                rulesData["crontab_info.hour"] = [{ required: true, message: "请输入时间", trigger: "blur" }]
                rulesData["crontab_info.day_of_week"] = [{ required: true, message: "请输入星期几", trigger: "blur" }]
                rulesData["crontab_info.day_of_month"] = [{ required: true, message: "请输入天", trigger: "blur" }]
                rulesData["crontab_info.month_of_year"] = [{ required: true, message: "请输入月", trigger: "blur" }]
            }else if(timeType == "clocked"){
                rulesData["clocked_info.clocked_time"] = [{ required: true, message: "请输入定时时间", trigger: "change" }]
                rulesData["one_off"] = [{ validator: validateOneOff, trigger: "blur" }]
            }else{
                
            }

            this.$nextTick(()=>{
                if (typeof this.$refs.roleForm != "undefined") {
                    this.$refs.roleForm.clearValidate()
                }
            })
            return rulesData
            
        },

    },
    mounted() {
        this.getData()
    },

    methods: {
        async getData(pager = 1) {
            this.listLoading = true
            this.page = pager
            let {
                page,
                limit,
                searchObj
            } = this
            let result = await this.$API.task.reqDataList({page,limit,...searchObj})
            if (result.code = 200) {
                this.dataList = result.data.items
                this.total = result.data.total
                this.listLoading = false
            }
        },
        // 设置条数
        handleSizeChange(event) {
            this.limit = event
            this.getData()
        },
        // 搜索
        search() {
            // 深拷贝
            this.searchObj = {
                ...this.searchTempObj
            }
            this.getData()
        },
        // 清空搜索
        clearSearch() {
            this.searchObj = this.searchTempObj = {}
            this.getData()
        },


        // 添加角色
        handleAdd() {
            this.dialogVisible = true;
            this.buttonLoading = false;
            // this.resetDataInfo()

            

        },
        // 更新数据
        async handleUpdate(row) {
            this.dialogVisible = true;
            this.buttonLoading = false;
            let result = await this.$API.task.reqdataInfo(row.id);
            if (result.code == 200) {
                this.dataInfo = result.data
                
            }
        },
        saveData(){
            this.buttonLoading = true;
            let {dataInfo,page} = this;
            this.$refs.roleForm.validate(async (valid) => {
               
                if (valid) {
                    let result = await this.$API.task.reqAddOrUpdate(dataInfo)
                    if (result.code == 201 || result.code == 200) {
                        this.$message({
                            type: 'success',
                            message: dataInfo.id ? '修改成功' : '添加成功'
                        })
                        this.getData(dataInfo.id ? page : 1)
                        this.clearData()
                    }
                    this.buttonLoading = false;
                }else{
                    this.$message({
                        type: "error",
                        message: dataInfo.id ? '修改失败' : '添加失败'
                    })
                    this.buttonLoading = false;
                    return false;
                }
            })
            
        },
        clearData(){
            this.dialogVisible = false;
            this.resetDataInfo()
            // 清空上一次的验证规则
            this.$nextTick(() => this.$refs.roleForm.clearValidate())
        },
        resetDataInfo() {

            this.dataInfo = {
                time_type:'interval',
                enabled:true,
                interval_info:{every:1,period:'days'},
                crontab_info:{},
                clocked_info:{},
                one_off:false
            }
        },
        // 删除单个数据
        handleDelete(row) {

            this.$confirm(`此操作将永久删除${row.name}该数据, 是否继续?`, '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }).then(async () => {
                let result = await this.$API.task.reqRemove(row.id)
                if (result.code = 204) {
                    this.$message({
                        type: 'success',
                        message: `删除${row.name}成功！`
                    })
                    this.getData(this.dataList.length > 1 ? this.page : this.page - 1)
                }

            }).catch(() => {
                this.$message({
                    type: 'info',
                    message: `已取消删除${row.name}！`
                });
            });
        },
        
        async changeStatus(row,index){
            let dataInfo = {
                id:row.id,
                enabled:row.enabled,
            }
            let result = await this.$API.task.reqAddOrUpdate(dataInfo)
            if (result.code == 200) {
                this.$message({
                    type: 'success',
                    message: '修改成功'
                })

            }
        },
        

    }
}
</script>
  
  <style scoped>

  </style>